﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Common
{
    /// <summary>
    /// WebSocketManage
    /// </summary>
    public class WebSocketConnectionManager
    {
        private static ConcurrentDictionary<string, WebSocket> _socketConcurrentDictionary = new ConcurrentDictionary<string, WebSocket>();

        public void AddSocket(WebSocket socket)
        {
            _socketConcurrentDictionary.TryAdd(Guid.NewGuid().ToString(), socket);
        }

        public async Task RemoveSocket(WebSocket socket)
        {
            _socketConcurrentDictionary.TryRemove(GetSocketId(socket), out WebSocket delSocket);
            await delSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "close by user", CancellationToken.None).ConfigureAwait(false);
        }

        public string GetSocketId(WebSocket socket)
        {
            return _socketConcurrentDictionary.FirstOrDefault(m => m.Value == socket).Key;
        }

        public ConcurrentDictionary<string, WebSocket> GetAll()
        {
            return _socketConcurrentDictionary;
        }

    }
}
